/**
 * 工具函数
 */

/**
 * 格式化日期为本地化字符串
 * @param date 日期对象
 * @returns 格式化后的字符串
 */
export const formatDate = (date: Date): string => {
    const options: Intl.DateTimeFormatOptions = {
        year: 'numeric',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
    };
    return date.toLocaleDateString(undefined, options);
};

/**
 * 将文件大小转换为人类可读格式
 * @param bytes 字节数
 * @param decimals 小数位数
 * @returns 格式化后的字符串
 */
export const formatFileSize = (bytes: number, decimals = 2): string => {
    if (bytes === 0) return '0 Bytes';

    const k = 1024;
    const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + ' ' + sizes[i];
};

/**
 * 生成唯一ID
 * @returns 唯一ID字符串
 */
export const generateId = (): string => {
    return Date.now().toString(36) + Math.random().toString(36).substring(2);
};

/**
 * 截断文本到指定长度
 * @param text 原始文本
 * @param maxLength 最大长度
 * @returns 截断后的文本
 */
export const truncateText = (text: string, maxLength: number): string => {
    if (text.length <= maxLength) return text;
    return text.substring(0, maxLength) + '...';
};

/**
 * 深度合并对象
 * @param target 目标对象
 * @param source 源对象
 * @returns 合并后的对象
 */
export const deepMerge = <T extends Record<string, any>>(target: T, source: Partial<T>): T => {
    const result = { ...target };

    Object.keys(source).forEach(key => {
        const targetValue = result[key];
        const sourceValue = source[key];

        if (
            typeof targetValue === 'object' &&
            targetValue !== null &&
            typeof sourceValue === 'object' &&
            sourceValue !== null &&
            !Array.isArray(targetValue) &&
            !Array.isArray(sourceValue)
        ) {
            result[key] = deepMerge(targetValue, sourceValue);
        } else if (sourceValue !== undefined) {
            result[key] = sourceValue;
        }
    });

    return result;
}; 